package com.icss.struct.dao;

import com.icss.struct.dto.SNSUser;
import com.icss.struct.dto.UserInfo;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class SNSUserDao {
    public List<SNSUser> selectAll(HashMap<String, String> param) {
        List<SNSUser> ulist = new ArrayList<>();

        // 2. 创建链接
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest?characterEncoding=utf8", "root", "root");

            // 3. 创建执行器：
            String sql = "SELECT id, su.uname, su.nickname, su.image, su.price, su.password, su.ldate FROM sns_user su";

            PreparedStatement ps = conn.prepareStatement(sql);
            // 4. 执行SQl,处理结果
            ResultSet rs = ps.executeQuery();

            // 处理结果集
            while (rs.next()) { // 有下一条记录并且指向这一行
                SNSUser item = new SNSUser();
                item.setId(rs.getInt(1));
                item.setUname(rs.getString(2));
                item.setNickname(rs.getString(3));
                item.setImg(rs.getString(4));
                item.setPrice(rs.getInt(5));
//                item.setPassword(rs.getString(6));
                item.setLdate(rs.getTimestamp(7));
                ulist.add(item);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            // 5. 关闭资源
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }


        return ulist;
    }

    public void deleteById(String id) {
        // 2. 创建链接
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest?characterEncoding=utf8", "root", "root");
            conn.setAutoCommit(false);
            // 3. 创建执行器：
            String sql = "delete from sns_user where id = ?";
            PreparedStatement ps = conn.prepareStatement(sql);

            ps.setString(1, id);

            // 4. 执行SQl,处理结果
            int r = ps.executeUpdate();
            if (r == 1) {
                conn.commit();
            } else {
                conn.rollback();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            // 5. 关闭资源
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
